package link.jfire.jnet.server.transfer.CompletionHandler;

import java.nio.channels.CompletionHandler;
import javax.annotation.Resource;
import link.jfire.baseutil.simplelog.ConsoleLogFactory;
import link.jfire.baseutil.simplelog.Logger;
import link.jfire.jnet.common.InternalResultContainer;
import link.jfire.jnet.common.buffer.ByteBuf;
import link.jfire.jnet.server.storage.ServerInternalResult;
import link.jfire.jnet.server.transfer.server.ServerChannelInfo;

@Resource
public class ChannelWriteHandler implements CompletionHandler<Integer, ServerInternalResult>
{
    private final Logger logger = ConsoleLogFactory.getLogger();
    
    @Override
    public void completed(Integer writeTotal, ServerInternalResult result)
    {
        ByteBuf<?> buf = (ByteBuf<?>) result.getData();
        buf.addReadIndex(writeTotal);
        if (buf.remainRead() > 0)
        {
            if (logger.isTraceEnabled())
            {
                logger.trace("向通道{}数据写入不完整,写入{},当前状态{}", result.getChannelInfo().getAddress(), writeTotal, buf);
            }
            result.getChannelInfo().write(result);
            return;
        }
        else
        {
            buf.release();
            ServerChannelInfo channelInfo = result.getChannelInfo();
            channelInfo.sendOne();
            InternalResultContainer.recycleServer(result);
            ServerInternalResult next = channelInfo.waitForSend();
            if (next != null)
            {
                next.getChannelInfo().write(next);
            }
            else
            {
                logger.trace("消息是空的，通道剩余是{}", channelInfo.left());
            }
        }
    }
    
    @Override
    public void failed(Throwable exc, ServerInternalResult entry)
    {
        logger.error("向socket通道{}写入信息失败，关闭通道,buffer状态是{}", entry.getChannelInfo().getAddress(), entry.getData(), exc);
        ((ByteBuf<?>) entry.getData()).release();
        entry.getChannelInfo().close();
    }
    
}
